package me.ezjs.framework.config;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class SpringContextUtil implements ApplicationContextAware {

	private static ApplicationContext applicationContext;

	private final static String[] DAO_SUFFIX = { "DaoImpl", "Dao" };

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		SpringContextUtil.applicationContext = applicationContext;
	}

	public static ApplicationContext getApplicationContext() {
		return applicationContext;
	}

	/**
	 * 从spring中获取bean.
	 * 
	 * @param name
	 * @return
	 */
	public static Object getBean(String name) {
		return applicationContext.getBean(name);
	}

	public static Object getDao(String className) {
		Object obj = null;
		for (String suffix : DAO_SUFFIX) {
			try {
				obj = applicationContext.getBean(className + suffix);
			} catch (NoSuchBeanDefinitionException e) {
				// Do Nothing.
			}
			if (obj != null) {
				break;
			}
		}
		return obj;
	}


}
